package com.education.user.controller.app;

import com.education.common.pojo.TStudent;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.QiniuUtil;
import com.education.common.utils.Token;
import com.education.user.config.BaiduAipContentCensor;
import com.education.user.feign.AuthClient;
import com.education.user.feign.SchoolClient;
import com.education.user.feign.StudentClient;
import com.education.user.feign.WisdomFeign;
import com.education.user.pojo.SendSmsUtil;
import com.education.user.pojo.User;
import com.education.user.pojo.UserVO;
import com.education.user.service.UserService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Api(tags = {"APP--用户信息"})
@RequestMapping("/app/user")
@RestController
@SuppressWarnings("all")
public class AppUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StudentClient studentClient;

    @Autowired
    private SchoolClient schoolClient;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private WisdomFeign wisdomFeign;
    @Autowired
    private BaiduAipContentCensor baiduAipContentCensor;

    /**
     * 1.学生APP获取验证码
     *
     * @param user
     * @return
     * @throws Exception
     */
    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码登陆使用", httpMethod = "POST")
    public ApiReturnObject sendCode(User user) throws Exception {
        //发送验证码
        if (user.getSysPhone() == "" && user.getSysPhone() == null) {
            return new ApiReturnObject("201", "手机号为空", "手机号为空");
        }
        String verifyCode3 = (int) ((Math.random() * 9 + 1) * 100000) + "";
        redisTemplate.opsForHash().put(user.getSysPhone(), "code", verifyCode3);
        redisTemplate.boundValueOps(user.getSysPhone()).expire(60, TimeUnit.SECONDS);
        String codeResult = SendSmsUtil.sendSmsTwo(user.getSysPhone(), verifyCode3);
        return new ApiReturnObject("200", codeResult, "");
    }

    /**
     * 1.学生APP手机号验证码登陆
     *
     * @param phone
     * @param code
     * @return
     */
    @ApiOperation(value = "验证码登陆", httpMethod = "POST")
    @PostMapping("/codeLogin")
    public ApiReturnObject login(String phone, String code) {
        Map<Object, Object> map = Maps.newHashMap();
        if ("".equals(phone) || phone == null || "".equals(code) || code == null) {
            return new ApiReturnObject("201", "用户名或验证码为空", map);
        } else {
            //查询该用户是否存在
            User appUser = new User();
            appUser.setSysPhone(phone);
            List<User> userList = userService.select(appUser);
            if (userList.size() == 0) {
                //用户不存在注册
                register(phone, code, code);
                String smsCode = (String) redisTemplate.opsForHash().get(phone, "code");
                if (code.equals(smsCode)) {
                    List<User> list = userService.select(appUser);
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(list.get(0), userVO);
                    //获取token
                    String token = authClient.getToken(list.get(0).getId().intValue());
                    userVO.setToken(token);
                    userVO.setShifouwanshan("0");
                    if (list.get(0).getSysState() == 1) {
                        return new ApiReturnObject("203", "该账号已被停用", map);
                    }
                    return new ApiReturnObject("200", "登陆成功", userVO);
                }
                return new ApiReturnObject("203", "验证码有误", map);
            } else {
                if (userList.get(0).getSysState() == 1) {
                    return new ApiReturnObject("203", "该账号已被停用", map);
                }
                if (StringUtils.isNotBlank(userList.get(0).getSysType()) && Arrays.asList("2", "3", "4").contains(userList.get(0).getSysType())) {
                    return new ApiReturnObject("203", "此平台仅限学生登录", map);
                }
                //获取验证码
                String smsCode = (String) redisTemplate.opsForHash().get(phone, "code");
                if (code.equals(smsCode)) {
                    UserVO userVO = new UserVO();
                    BeanUtils.copyProperties(userList.get(0), userVO);
                    //获取token
                    String token = authClient.getToken(userList.get(0).getId().intValue());
                    userVO.setToken(token);
                    userVO.setShifouwanshan("0");
                    return new ApiReturnObject("200", "登陆成功", userVO);
                } else {
                    return new ApiReturnObject("203", "验证码有误", map);
                }
            }
        }
    }

    /**
     * 学生端APP注册接口
     *
     * @param phone
     * @param code
     * @return
     */
    @ApiOperation(value = "手机号注册", httpMethod = "POST")
    @PostMapping("/registers")
    public ApiReturnObject register(String phone, String code, String password) {
        if ("".equals(phone) || phone == null || "".equals(code) || code == null) {
            return new ApiReturnObject("201", "用户名或验证码为空", null);
        } else {
            //查询该用户是否存在
            User appUser = new User();
            appUser.setSysPhone(phone);
            List<User> userList = userService.select(appUser);
            if (userList.size() > 0) {
                return new ApiReturnObject("202", "该用户已存在 请重新注册", null);
            } else {
                //获取验证码
                String smsCode = (String) redisTemplate.opsForHash().get(phone, "code");
                if (code.equals(smsCode)) {
                    //添加用户信息 完成注册
                    User user = new User();
                    user.setSysPhone(phone);
                    user.setSysRelname("匿名");
                    //默认头像
                    user.setSysIco("4.0defaultavatar.png");
                    user.setCreateTime(new Date());
                    //1表示该用户是学生
                    //user.setSysType("1");
                    //默认设为0
                    user.setSchoolId(0);
                    //默认设为0
                    user.setClassId(0);
                    //用户状态 0 正常  1 停用
                    user.setSysState(0);
                    user.setCustomerType("1");
                    user.setPrice(0);
                    user.setLogins(0);
                    try {
                        user.setSysPassword(Token.getMD5String("123456"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    userService.insert(user);
                    //远程调用 修改手机号对应学生的userId
                    schoolClient.updateByFeign(Math.toIntExact(user.getId()), phone);
                    return new ApiReturnObject("200", "注册成功", null);
                } else {
                    return new ApiReturnObject("203", "验证码有误", null);
                }
            }
        }
    }

    @ApiOperation(value = "注册添加密码", httpMethod = "POST")
    @PostMapping("/registersByPassword")
    public ApiReturnObject register(String phone, String password) {
        if ("".equals(phone) || phone == null || "".equals(password) || password == null) {
            return new ApiReturnObject("201", "手机号或密码为空", "手机号或密码为空");
        } else {
            User appUser = new User();
            appUser.setSysPhone(phone);
            List<User> userList = userService.select(appUser);
            if (userList.size() == 0) {
                return new ApiReturnObject("202", "该用户不存在 无法修改", "该用户不存在 无法修改");
            } else {
                User user = new User();
                user.setId(userList.get(0).getId());
                try {
                    user.setSysPassword(Token.encoderByMd5(password));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                userService.update(user);
                return new ApiReturnObject("200", "密码修改成功", "密码修改成功");
            }
        }
    }


    @ApiOperation(value = "修改手机号", httpMethod = "POST")
    @PostMapping("/updateByPhone")
    public ApiReturnObject updateByPhone(String phone, String newPhone, String code, String newcode) {
        if ("".equals(phone) || phone == null || "".equals(code) || code == null) {
            return new ApiReturnObject("201", "旧手机号或验证码为空", "旧手机号或验证码为空");
        } else {
            User sysAppUser = new User();
            sysAppUser.setSysPhone(phone);
            List<User> userList = userService.select(sysAppUser);
            //获取旧手机号验证码
            String smsCode2 = (String) redisTemplate.opsForHash().get(phone, "code");
            if (code.equals(smsCode2)) {
                if (userList.size() != 0) {
                    if ("".equals(newcode) || newcode == null || "".equals(newPhone) || newPhone == null) {
                        return new ApiReturnObject("202", "新手机号或验证码为空", "新手机号或验证码为空");
                    } else {
                        //获取验证码
                        String smsCode = (String) redisTemplate.opsForHash().get(newPhone, "code");
                        if (newcode.equals(smsCode)) {
                            User appUser = new User();
                            appUser.setId(userList.get(0).getId());
                            //根据新手机号查询用户是否存在  存在则无法修改
                            User appUser1 = new User();
                            appUser1.setSysPhone(newPhone);
                            List<User> select = userService.select(appUser1);
                            if (select.size() == 0) {
                                appUser.setSysPhone(newPhone);
                                userService.update(appUser);
                                return new ApiReturnObject("200", "修改成功", "修改成功");
                            } else {
                                return new ApiReturnObject("206", "新手机号已存在 请重新输入", "新手机号已存在 请重新输入");
                            }
                        } else {
                            return new ApiReturnObject("203", "新验证码有误", "新验证码有误");
                        }
                    }
                } else {
                    return new ApiReturnObject("204", "旧手机号有误", "旧手机号有误");
                }
            } else {
                return new ApiReturnObject("205", "旧验证码有误", "旧验证码有误");
            }
        }
    }


    @ApiOperation(value = "修改密码", httpMethod = "POST")
    @PostMapping("/updateByPassword")
    public ApiReturnObject updateByPassword(String phone, String code, String password) {
        if ("".equals(phone) || phone == null || "".equals(code) || code == null) {
            return new ApiReturnObject("201", "手机号或验证码为空", "手机号或验证码为空");
        } else {
            User appUser = new User();
            appUser.setSysPhone(phone);
            List<User> userList = userService.select(appUser);
            if (userList.size() != 0) {
                //获取验证码
                String smsCode = (String) redisTemplate.opsForHash().get(phone, "code");
                if (code.equals(smsCode)) {
                    if (password.length() != 0 || "".equals(password)) {
                        User sysAppUser = new User();
                        sysAppUser.setId(userList.get(0).getId());
                        try {
                            sysAppUser.setSysPassword(Token.encoderByMd5(password));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        userService.update(sysAppUser);
                        return new ApiReturnObject("200", "密码已修改", "密码已修改");
                    } else {
                        return new ApiReturnObject("204", "未输入密码", "未输入密码");
                    }
                } else {
                    return new ApiReturnObject("202", "验证码有误", "验证码有误");
                }
            } else {
                return new ApiReturnObject("203", "该手机号不存在", "该手机号不存在");
            }
        }
    }

    @ApiOperation(value = "绑定学校和班级", httpMethod = "POST")
    @PostMapping("/BindingBySchoolAndClass")
    public ApiReturnObject binding(String idcardno, String studentName, Integer userId) {
        if ("".equals(idcardno) || idcardno == null || "".equals(studentName) || studentName == null || userId == null) {
            return new ApiReturnObject("201", "参数缺失", "参数缺失");
        } else {
            Map<String, Object> tStudent = studentClient.findByNameAndIdcardno(studentName, idcardno, userId);
            if (tStudent == null) {
                return new ApiReturnObject("202", "该学生不存在或已被绑定", "该学生不存在或已被绑定");
            } else {
                User appUser = new User();
                appUser.setSchoolId(Integer.parseInt(tStudent.get("schoolId").toString()));//学校id
                appUser.setClassId(Integer.parseInt(tStudent.get("classId").toString()));//班级id
                appUser.setIdcardno(idcardno);//身份证号
                appUser.setSysSex(tStudent.get("sex").toString());// 1 男   2 女
                appUser.setSysState(0);//状态
                User user = userService.selectByPrimaryKey(userId);
                if (user == null) {
                    return new ApiReturnObject("203", "该用户不存在", "该用户不存在");
                } else {
                    appUser.setId(Long.valueOf(userId));
                }
                userService.update(appUser);
                User sysAppUser = userService.selectByPrimaryKey(userId);
                Integer teaUserId = userService.selectUserIdBySchoolId(Integer.parseInt(tStudent.get("schoolId").toString()));
                //用户添加成功分配共享专业课程
                wisdomFeign.insUserBuy(userId, teaUserId);
                return new ApiReturnObject("200", "绑定成功", sysAppUser);
            }
        }
    }

    @ApiOperation(value = "查询个人详情", httpMethod = "GET")
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer userId) {
        if (userId == null) {
            return new ApiReturnObject("201", "参数缺失", "参数缺失");
        }
        UserVO userVO = new UserVO();
//        SysAppUserVO sysAppUserVO = new SysAppUserVO();
        User sysAppUser = userService.selectByPrimaryKey(userId);
        if (sysAppUser == null) {
            return new ApiReturnObject("202", "该用户不存在", "该用户不存在");
        }
        //copy实体类数据
        BeanUtils.copyProperties(sysAppUser, userVO);
        String schoolName = schoolClient.findBySchoolId(sysAppUser.getSchoolId());
        if (schoolName == null) {
            userVO.setSchoolName("当前账号没有绑定学校");
        } else {
            userVO.setSchoolName(schoolName);
        }
        return new ApiReturnObject("200", "查询成功", userVO);
    }


    /**
     * 学生APP
     *
     * @param sysAppUser
     * @return
     */
    @ApiOperation(value = "修改用户名和头像", httpMethod = "POST")
    @PostMapping("/updataByNameAndImg")
    public ApiReturnObject updataByNameAndImg(User sysAppUser) {
        if (sysAppUser.getId() == null) {
            return new ApiReturnObject("201", "userId为空", "userId为空");
        }
        if (StringUtils.isNotBlank(sysAppUser.getSysIco()) && baiduAipContentCensor.AipImage(sysAppUser.getSysIco()) == 2) {
            QiniuUtil.deleteFileFromQiniu(sysAppUser.getSysIco());
            return new ApiReturnObject("201", "头像违规", "头像违规");
        }
        if (StringUtils.isNotBlank(sysAppUser.getSysRelname()) && baiduAipContentCensor.AipText(sysAppUser.getSysRelname()) == 2) {
            return new ApiReturnObject("201", "名称违规", "名称违规");
        }
        //修改用户表信息
        Integer i = userService.update(sysAppUser);
        //修改学生表信息
        TStudent tStudent = new TStudent();
        tStudent.setUserId(sysAppUser.getId().intValue());
        if (StringUtils.isNotBlank(sysAppUser.getSysRelname())) {
            tStudent.setStudentName(sysAppUser.getSysRelname());
        }
        if (StringUtils.isNotBlank(sysAppUser.getSysIco())) {
            tStudent.setImgUrl(sysAppUser.getSysIco());
        }
        String result = studentClient.updateByStudentName(tStudent);
        return new ApiReturnObject("200", "修改成功", "修改成功");
    }

    /**
     * feign : 根据用户id查询用户信息
     */
    @GetMapping("/findByUserId")
    public Map<String, String> findByUserId(Integer userId) {
        User sysAppUser = userService.selectByPrimaryKey(userId);
        if (sysAppUser != null) {
            Map<String, String> map = new HashMap<>();
            map.put("image", sysAppUser.getSysIco());//头像
            map.put("name", sysAppUser.getSysRelname());//姓名
            return map;
        } else {
            return null;
        }
    }
//    @PostMapping("/updatesign")
//    public ApiReturnObject updatesign(User user){
//        Date date = new Date();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String format = simpleDateFormat.format(date);
//        user.setSignTime(format);
//        userService.update(user);
//        return new ApiReturnObject("200","修改成功","修改成功");
//    }

}
